<template>
  <div class="upload-container">
    <GreenSuccessDialog ref="successDialogRef" />
    <div v-if="isLoading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <span>加载中...</span>
    </div>
    <div v-else class="upload-content">
      <div class="upload-card">
        <h2>创建新专辑</h2>
        <form class="upload-form" @submit.prevent="handleUpload">
          <div class="form-group">
            <label for="albumTitle">专辑标题 *</label>
            <input
              id="albumTitle"
              type="text"
              v-model="albumForm.title"
              placeholder="请输入专辑标题"
              class="form-input"
              :class="{ 'is-invalid': errors.title }"
              maxlength="100"
              @blur="validateField('title')"
            />
            <span v-if="errors.title" class="error-message">{{ errors.title }}</span>
          </div>
          <div class="form-group">
            <label for="albumDescription">专辑描述</label>
            <textarea
              id="albumDescription"
              v-model="albumForm.description"
              placeholder="请输入专辑描述"
              class="form-input description-textarea"
              rows="4"
              maxlength="500"
              :class="{ 'is-invalid': errors.description }"
              @blur="validateField('description')"
            ></textarea>
            <span v-if="errors.description" class="error-message">{{ errors.description }}</span>
          </div>
          <div class="form-group">
            <label>专辑封面 *</label>
            <div
              class="file-upload-area"
              @drop.prevent="(e) => handleCoverDrop(e)"
              @dragover.prevent
            >
              <input
                ref="coverInput"
                type="file"
                accept="image/*"
                @change="(e) => handleCoverSelect(e)"
                class="file-input"
              />
              <div v-if="!coverPreviewUrl" class="upload-placeholder">
                <div class="upload-icon">📷</div>
                <p>点击或拖拽上传封面</p>
              </div>
              <div v-else class="preview-container">
                <img :src="coverPreviewUrl" alt="封面预览" class="cover-preview" />
                <button type="button" class="remove-btn" @click="removeFile('cover')">×</button>
              </div>
            </div>
            <span v-if="errors.coverImage" class="error-message">{{ errors.coverImage }}</span>
          </div>
          <button type="submit" class="btn-primary" :disabled="uploading">
            <span v-if="!uploading">创建专辑</span>
            <span v-if="uploading">创建中...</span>
          </button>
          <div v-if="uploadProgress > 0 && uploadProgress < 100" class="progress-bar">
            <div class="progress" :style="{ width: uploadProgress + '%' }"></div>
            <span>{{ uploadProgress }}%</span>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createAlbum } from '../api/album'
import GreenSuccessDialog from '../components/GreenSuccessDialog.vue'
const router = useRouter()
const isLoading = ref(false)
const successDialogRef = ref(null)
const coverInput = ref(null)
// 专辑表单数据
const albumForm = ref({
  title: '',
  description: '',
})
// 表单错误信息
const errors = ref({
  title: '',
  description: '',
  coverImage: '',
})
const coverImage = ref(null)
const coverPreviewUrl = ref('')
const uploading = ref(false)
const uploadProgress = ref(0)

// 表单验证规则
const validationRules = {
  title: {
    required: true,
    message: '请输入专辑标题',
    maxLength: 100,
  },
  description: {
    maxLength: 500,
  },
  coverImage: {
    required: true,
    message: '请选择封面图片',
  },
}

// 验证单个字段
const validateField = (field) => {
  const value = field === 'coverImage' ? coverImage.value : albumForm.value[field]
  const rules = validationRules[field]
  let error = ''

  if (!rules) return

  // 处理必填字段
  if (rules.required && !value) {
    error = rules.message
  }
  // 处理最大长度
  else if (rules.maxLength && typeof value === 'string' && value.length > rules.maxLength) {
    error = `${field === 'title' ? '标题' : '描述'}长度不能超过${rules.maxLength}个字符`
  }

  errors.value[field] = error
}

// 验证整个表单
const validateForm = () => {
  // 重置所有错误
  Object.keys(errors.value).forEach((field) => {
    errors.value[field] = ''
  })

  // 验证所有字段
  Object.keys(validationRules).forEach(validateField)

  // 检查是否有错误
  return !Object.values(errors.value).some((error) => error)
}

// 处理文件选择
const handleCoverSelect = (event) => {
  const file = event.target.files[0]
  if (file) {
    coverImage.value = file
    coverPreviewUrl.value = URL.createObjectURL(file)
    validateField('coverImage')
  }
}

// 处理文件拖拽
const handleCoverDrop = (event) => {
  const file = event.dataTransfer.files[0]
  if (file && file.type.startsWith('image/')) {
    coverImage.value = file
    coverPreviewUrl.value = URL.createObjectURL(file)
    validateField('coverImage')
  }
}

// 移除文件
const removeFile = (type) => {
  if (type === 'cover') {
    coverImage.value = null
    coverPreviewUrl.value = ''
    validateField('coverImage')
    // 清空文件输入
    if (coverInput.value) {
      coverInput.value.value = ''
    }
  }
}

// 重置表单
const resetForm = () => {
  albumForm.value = {
    title: '',
    description: '',
  }
  coverImage.value = null
  coverPreviewUrl.value = ''
  errors.value = {
    title: '',
    description: '',
    coverImage: '',
  }
  uploadProgress.value = 0
}

// 处理专辑上传
const handleUpload = async () => {
  if (!validateForm()) {
    return
  }

  uploading.value = true
  uploadProgress.value = 0

  try {
    const formData = new FormData()
    formData.append('title', albumForm.value.title)
    formData.append('description', albumForm.value.description)
    if (coverImage.value) {
      formData.append('coverImage', coverImage.value)
    }

    // 调用创建专辑API，并跟踪进度
    const response = await createAlbum(formData, (progressEvent) => {
      if (progressEvent.lengthComputable) {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        uploadProgress.value = percentCompleted
      }
    })

    uploadProgress.value = 100

    // 显示成功消息
    if (response && response.code === 200) {
      // 先显示成功消息，再重置表单
      successDialogRef.value
        .show({
          message: '专辑创建成功！是否立即上传音乐？',
          title: '成功提示',
          confirmText: '上传音乐',
          cancelText: '稍后再说',
          showCancel: true,
        })
        .then(() => {
          // 重置表单
          resetForm()
          // 跳转到上传音乐页面，并传递专辑ID
          router.push({
            path: '/upload',
            query: { albumId: response.data.id },
          })
        })
        .catch(() => {
          // 重置表单
          resetForm()
          // 用户取消操作
          ElMessage.success({
            message: '您可以稍后在专辑详情页上传音乐',
            customClass: 'success-message',
          })
        })
    } else {
      ElMessage({
        message: response?.msg || '创建专辑失败',
        type: 'error',
        showClose: true,
      })
      uploadProgress.value = 0
    }
  } catch (error) {
    console.error('创建专辑失败:', error)
    ElMessage.error('创建专辑失败，请重试')
    uploadProgress.value = 0
  } finally {
    uploading.value = false
  }
}

// 返回首页
const toHome = () => {
  router.push('/')
}
</script>

<style scoped>
/* 覆盖Element Plus消息样式 */
:deep(.el-message.success-message) {
  background-color: rgba(52, 199, 89, 0.1) !important;
  border-color: var(--success-color) !important;
}

:deep(.el-message.success-message .el-message__content) {
  color: var(--success-color) !important;
}

:deep(.el-message.success-message .el-message__icon) {
  color: var(--success-color) !important;
}

:deep(.el-message-box.success-message-box) {
  border-color: var(--success-color) !important;
}

:deep(.el-message-box.success-message-box .el-message-box__header) {
  border-bottom-color: var(--success-color) !important;
}

:deep(.el-message-box.success-message-box .el-message-box__title) {
  color: var(--success-color) !important;
}

:deep(.el-message-box.success-message-box .el-message-box__status) {
  color: var(--success-color) !important;
}

.upload-container {
  min-height: 100vh;
  padding: 40px 20px;
  /* background: linear-gradient(135deg, #f8fff8 0%, #f0f9f0 100%); */
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top: 4px solid #27ae60;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.upload-content {
  width: 100%;
  max-width: 500px;
}

.upload-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(39, 174, 96, 0.15);
  border: 1px solid rgba(39, 174, 96, 0.1);
  padding: 40px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
  cursor: pointer;
}

.music-icon {
  width: 32px;
  height: 32px;
  color: var(--success-color);
  margin-right: 10px;
}

.logo span {
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
}

h2 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 600;
}

.upload-form {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  text-align: left;
}

.form-group label {
  font-weight: 600;
  margin-bottom: 8px;
  color: #2c3e50;
}

.form-input,
.form-textarea {
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: white;
  width: 100%;
  font-family: inherit;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: var(--success-color);
  box-shadow: 0 0 0 3px rgba(39, 174, 96, 0.1);
}

.description-textarea {
  resize: vertical; /* 只允许上下拉伸 */
  min-height: 100px; /* 设置最小高度 */
  max-height: 300px; /* 设置最大高度 */
}

.form-input.is-invalid,
.form-textarea.is-invalid {
  border-color: #ff4757;
}

.error-message {
  color: #ff4757;
  font-size: 14px;
  margin-top: 4px;
}

/* 文件上传区域样式 */
.file-upload-area {
  position: relative;
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 30px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #f9f9f9;
}

.file-upload-area:hover {
  border-color: var(--success-color);
  background-color: #f8fff8;
}

.file-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #666;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.upload-placeholder p {
  margin: 0;
  font-size: 16px;
  color: #666;
}

.preview-container {
  position: relative;
  display: inline-block;
}

.cover-preview {
  max-width: 100%;
  max-height: 200px;
  border-radius: 8px;
  object-fit: cover;
}

.remove-btn {
  position: absolute;
  top: -10px;
  right: -10px;
  background: #ff4757;
  color: white;
  border: none;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  font-size: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-btn:hover {
  background: #ff3838;
}

.btn-primary {
  width: 100%;
  padding: 14px 28px;
  background: linear-gradient(135deg, #27ae60, #2ecc71);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(39, 174, 96, 0.3);
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(39, 174, 96, 0.4);
}

.btn-primary:disabled {
  background: linear-gradient(135deg, #bdc3c7, #95a5a6);
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background-color: #e8f5e8;
  border-radius: 4px;
  overflow: hidden;
  margin-top: 20px;
  position: relative;
}

.progress {
  height: 100%;
  background: linear-gradient(90deg, #27ae60, #2ecc71);
  transition: width 0.3s ease;
  border-radius: 4px;
}

.progress-bar span {
  position: absolute;
  top: -20px;
  right: 0;
  color: var(--success-color);
  font-size: 14px;
  font-weight: 600;
}

@media (max-width: 768px) {
  .upload-card {
    padding: 30px 20px;
    margin: 20px;
  }
}
</style>
